﻿/// <reference path="~/app/libs/sencha-touch-debug.js" />
Ext.define('iMobileS.view.CustomerContainer', {
    extend: 'Ext.form.Panel',
    alias: "widget.customercontainer",
    requires: [
                'Ext.form.FieldSet'
            ],
    initialize: function () {
        this.callParent(arguments);

        var backbutton = {
            xtype: "button",
            text: "Back",
            ui: "back",
            handler: this.onBackToCheckoutContainer,
            scope: this
        }

        //Define for top toolbar
        var topToolbar = {
            xtype: "toolbar",
            title: 'Order information',
            docked: "top",
            items: [
                backbutton,
                {
                    xtype: "spacer"
                }
            ]
        };

        //indicate require field
        var indicateRequire = {
            xtype: 'panel',
            style: 'margin-top:5px;',
            html: '<div style=\"color: #C33;\">* Indicates required fields</div>'
        }

        //Define mailingFieldsSet for form
        var customerFieldsSet = {
            xtype: 'fieldset',
            title: 'Order Information',
            items: [
                     {
                         xtype: 'textfield',
                         id: 'ShipName',
                         name: 'ShipName',
                         label: '<table cellspacing=\"0\" cellpadding=\"0\"><tr><td style=\"vertical-align: top; width:5px;\"><span class=\"require\">*</span></td><td style=\"padding-left:5px;\">Name</td></tr></table>',
                         labelWidth: "35%"
                     }, {
                         xtype: 'textfield',
                         id: "ShipAddress",
                         name: "ShipAddress",
                         label: '<table cellspacing=\"0\" cellpadding=\"0\"><tr><td style=\"vertical-align: top; width:5px;\"><span class=\"require\">*</span></td><td style=\"padding-left:5px;\">Address</td></tr></table>',
                         labelWidth: "35%"
                     }, {
                         xtype: 'textfield',
                         id: 'ShipCity',
                         name: 'ShipCity',
                         label: '<table cellspacing=\"0\" cellpadding=\"0\"><tr><td style=\"vertical-align: top; width:5px;\"><span class=\"require\">*</span></td><td style=\"padding-left:5px;\">City</td></tr></table>',
                         valueField: 'Value',
                         labelWidth: "35%"
                     }, {
                         xtype: 'datepickerfield',
                         picker: { xtype: 'datepicker', slotOrder: ["month", "day", "year"] },
                         id: 'RequiredDate',
                         name: 'RequiredDate',
                         value: new Date(),
                         label: '<table cellspacing=\"0\" cellpadding=\"0\"><tr><td style=\"vertical-align: top; width:5px;\"><span class=\"require\">*</span></td><td style=\"padding-left:5px;\">Required date</td></tr></table>',
                         labelWidth: "35%"
                     }, {
                         xtype: 'textfield',
                         id: 'ShipRegion',
                         name: 'ShipRegion',
                         label: '<table cellspacing=\"0\" cellpadding=\"0\"><tr><td style=\"vertical-align: top; width:5px;\"><span class=\"require\">*</span></td><td style=\"padding-left:5px;\">Region</td></tr></table>',
                         labelWidth: "35%"
                     }, {
                         xtype: 'textfield',
                         id: 'ShipPostalCode',
                         name: 'ShipPostalCode',
                         label: '<table cellspacing=\"0\" cellpadding=\"0\"><tr><td style=\"vertical-align: top; width:5px;\"><span class=\"require\">*</span></td><td style=\"padding-left:5px;\">Email</td></tr></table>',
                         labelWidth: "35%"
                     }, {
                         xtype: 'textfield',
                         id: 'ShipCountry',
                         name: 'ShipCountry',
                         label: '<table cellspacing=\"0\" cellpadding=\"0\"><tr><td style=\"vertical-align: top; width:5px;\"><span class=\"require\">*</span></td><td style=\"padding-left:5px;\">Country</td></tr></table>',
                         labelWidth: "35%"
                     }, {
                         xtype: 'textfield',
                         id: 'Freight',
                         name: 'Freight',
                         label: '<table cellspacing=\"0\" cellpadding=\"0\"><tr><td style=\"vertical-align: top; width:5px;\"><span class=\"require\">*</span></td><td style=\"padding-left:5px;\">Freight</td></tr></table>',
                         labelWidth: "35%"
                     }, {
                         xtype: 'selectfield',
                         id: 'Customers',
                         name: 'Customers',
                         label: '<table cellspacing=\"0\" cellpadding=\"0\"><tr><td style=\"vertical-align: top; width:5px;\"><span class=\"require\">*</span></td><td style=\"padding-left:5px;\">Customers</td></tr></table>',
                         displayField: 'CompanyName',
                         store: 'Customers',
                         valueField: 'CustomerID',
                         labelWidth: "35%"
                     }, {
                         xtype: "selectfield",
                         id: "Shippers",
                         name: "Shippers",
                         label: '<table cellspacing=\"0\" cellpadding=\"0\"><tr><td style=\"vertical-align: top; width:5px;\"><span class=\"require\">*</span></td><td style=\"padding-left:5px;\">Shippers</td></tr></table>',
                         displayField: 'CompanyName',
                         store: 'Shippers',
                         valueField: 'ShipperID',
                         labelWidth: "35%"
                     }, {
                         xtype: "selectfield",
                         id: "Employees",
                         name: "Employees",
                         label: '<table cellspacing=\"0\" cellpadding=\"0\"><tr><td style=\"vertical-align: top; width:5px;\"><span class=\"require\">*</span></td><td style=\"padding-left:5px;\">Employees</td></tr></table>',
                         displayField: 'LastName',
                         store: 'Employees',
                         valueField: 'EmployeeID',
                         labelWidth: "35%"
                     }
                ]
        }

        //Define next button
        var saveCustomerFieldSet = {
            xtype: 'fieldset',
            items: [{
                xtype: 'button',
                ui: 'action',
                text: 'Submit',
                handler: this.onSaveCustomer,
                scope: this
            }]
        }

        this.add([topToolbar, indicateRequire, customerFieldsSet, saveCustomerFieldSet]);
    },
    onSaveCustomer: function () {
        var formValues = this.getValues();
        if (formValues['ShipName'] == '') {
            Ext.Msg.alert('Submit', 'Full name is required.', Ext.emptyFn);
        }
        else if (formValues['ShipAddress'] == '') {
            Ext.Msg.alert('Submit', 'Address is required.', Ext.emptyFn);
        }
        else if (new Date(formValues['RequiredDate'].getFullYear(), formValues['RequiredDate'].getMonth(), formValues['RequiredDate'].getDate(), 0, 0, 0, 0) < new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate(), 0, 0, 0, 0)) {
            Ext.Msg.alert('Submit', 'Required date is lower current date.', Ext.emptyFn);
        }
        else if (formValues['ShipCity'] == '') {
            Ext.Msg.alert('Submit', 'City name is required.', Ext.emptyFn);
        }
        else if (formValues['ShipRegion'] == '') {
            Ext.Msg.alert('Submit', 'Region is required.', Ext.emptyFn);
        }
        else if (formValues['ShipPostalCode'] == '') {
            Ext.Msg.alert('Submit', 'Email is required.', Ext.emptyFn);
        }
        else if (!this.validateEmail(formValues['ShipPostalCode'])) {
            Ext.Msg.alert('Submit', 'E-mail is not valid', Ext.emptyFn);
        }
        else if (formValues['ShipCountry'] == '') {
            Ext.Msg.alert('Submit', 'Country is required.', Ext.emptyFn);
        }
        else if (formValues['Freight'] == '') {
            Ext.Msg.alert('Submit', 'Freight is required.', Ext.emptyFn);
        }
        else if (isNaN(formValues['Freight'])) {
            Ext.Msg.alert('Submit', 'Freight is number.', Ext.emptyFn);
        }
        else if (formValues['Customers'].indexOf('ext') == '') {
            Ext.Msg.alert('Submit', 'Customers is required.', Ext.emptyFn);
        }
        else if (formValues['Shippers'] == 0) {
            Ext.Msg.alert('Submit', 'Shippers is required.', Ext.emptyFn);
        }
        else if (formValues['Employees'] == 0) {
            Ext.Msg.alert('Submit', 'Employees is required.', Ext.emptyFn);
        }
        else {
            // Get selected productids            
            var objProduct = Ext.getStore('Products');
            var productCount = objProduct.getCount();
            var productdetails = [];
            if (productCount > 0) {
                for (var i = 0; i < productCount; i++) {
                    var record = objProduct.getAt(i);
                    var productId = record.data.ProductID;
                    var quantity = record.data.Quantity;
                    var price = record.data.UnitPrice;
                    productdetails.push({ ProductId: productId, Quantity: quantity, UnitPrice: price, Discount: 0 });
                }
            }
            var orderDetailJSON = Ext.encode(productdetails);

            // Get order info 
            var shipName = Ext.getCmp('ShipName').getValue();
            var freight = Ext.getCmp('Freight').getValue();
            var shipVia = Ext.getCmp('Shippers').getValue();
            var employeeId = Ext.getCmp('Employees').getValue();
            var address = Ext.getCmp('ShipAddress').getValue();
            var customerId = Ext.getCmp('Customers').getValue();
            var city = Ext.getCmp('ShipCity').getValue();
            var region = Ext.getCmp('ShipRegion').getValue();
            var postalCode = Ext.getCmp('ShipPostalCode').getValue();
            var country = Ext.getCmp('ShipCountry').getValue();
            var requiredDate = Ext.getCmp('RequiredDate').getValue();

            var orderinfo = { CustomerId: customerId, EmployeeId: employeeId, ShipVia: shipVia, ShipName: shipName, Freight: freight,
                ShipAddress: address, ShipCity: city, ShipRegion: region, ShipPostalCode: postalCode, ShipCountry: country, RequiredDate: requiredDate
            }
            var orderJSON = Ext.encode(orderinfo);


            Ext.Ajax.request({
                url: appPath + 'Home/InsertOrder',
                method: 'POST',
                params: {
                    orders: orderJSON,
                    orderdetails: orderDetailJSON
                },
                success: function (result) {
                    if (result) {
                        Ext.Msg.alert("Thank you", "Thank you for ordering products from Southern supper markets", this.onBackToHome, this);
                    }

                },
                failure: function (result) {
                    Ext.Msg.alert('Error', 'Have an error when get data from server.', Ext.emptyFn);
                }
            });
        }
    },
    onBackToCheckoutContainer: function () {
        if (this.validate()) {
            Ext.Msg.confirm("Confirmation", "Do you want to save your selection?", this.onSaveContestWithConfirm, this);
        }
        else {
            this.fireEvent("onBackToCheckoutContainer", this);
        }
    },
    onSaveContestWithConfirm: function (msg) {

        if (msg == "yes") {
            this.onSaveCustomer();
        } else {
            this.fireEvent("onBackToCheckoutContainer", this);
        }
    },
    validateEmail: function (email) {
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        return reg.test(email);
    },
    onBackToHome: function () {
        this.fireEvent('onBackToHome', this);
    },
    validate: function () {
        return true;
    }
});